package com.crm.crm.controller;

import com.alibaba.fastjson.JSON;
import com.crm.crm.service.CrmPartnerService;
import com.crm.entity.*;
import com.crm.model.JsonMessage;
import com.crm.model.Telephone;
import com.crm.model.UserInfo;
import com.crm.security.AuthUserDetail;
import com.crm.system.service.SysDictService;
import com.crm.system.service.SysRegionService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@Api(value = "伙伴信息接口")
@RequestMapping("/user/partner")
public class CrmPartnerController {
    @Autowired
    private CrmPartnerService crmPartnerService;

    @Autowired
    private SysDictService dictService;

    @Autowired
    private SysRegionService regionService;


    /**
     * 查询cr_partner表所有信息
     *
     * @param authentication
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "查询cr_partner表所有信息")
    @PostMapping("findAll")
    @ResponseBody
    public JsonMessage findAll(
            Authentication authentication,
            @RequestParam(defaultValue = "1") int pageIndex,
            @RequestParam(defaultValue = "10") int pageSize) {
        JsonMessage message = new JsonMessage();
        PageInfo<Partner> page = crmPartnerService.findAll(pageIndex, pageSize);
        message.setData(page);
        return message;
    }


    /**
     * 响应根据partner_type查询
     *
     * @param authentication
     * @param partnerType
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "响应根据partner_type查询")
    @PostMapping("findByPartType")
    @ResponseBody
    public JsonMessage findByPartType(
            Authentication authentication, String createId,
            Integer partnerType,
            @RequestParam(defaultValue = "1") int pageIndex,
            @RequestParam(defaultValue = "10") int pageSize) {
        JsonMessage message = new JsonMessage();
        PageInfo<Partner> page = crmPartnerService.findByPartType(partnerType, createId, pageIndex, pageSize);
        message.setData(page);

        return message;
    }

    @ApiOperation(value = "响应根据创建者查询")
    @PostMapping("findByCreatUser")
    @ResponseBody
    public JsonMessage findByCreatUser(
            Authentication authentication,
            String partnerType, @RequestParam(defaultValue = "1") int pageIndex,
            @RequestParam(defaultValue = "10") int pageSize) {
        AuthUserDetail detail = (AuthUserDetail) authentication.getDetails();
        JsonMessage message = new JsonMessage();
        PageInfo<Partner> page = crmPartnerService.findByCreatUser(detail.getUserId(), partnerType, pageIndex, pageSize);
        message.setData(page);
        return message;
    }


    //响应插入所有信息
    @ApiOperation(value = "响应插入所有信息")
    @PostMapping("add")
    @ResponseBody
    public JsonMessage addPartner(
            Authentication authentication,
            @RequestBody Partner partner) {
        JsonMessage message = new JsonMessage();
        AuthUserDetail detail = (AuthUserDetail) authentication.getDetails();
        partner.setPartnerId(UUID.randomUUID().toString());
        partner.setCreateTime(new Date());
        partner.setUpdateTime(new Date());
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        partner.setTime(sd.format(new Date()));
        partner.setDisabled(0);
        partner.setEmail(partner.getEmail().trim());
        partner.setWeixin(partner.getWeixin().trim());
        partner.setCreateUserId(detail.getUserId());
        int count = 0;
        int a = 0;
        if (partner.getTelephone() != null && !"".equals(partner.getTelephone())) {
            if (crmPartnerService.findByOnly(partner.getCreateUserId(), partner.getTelephone(), partner.getPartnerType()) > 0) {
                message.setData(0);
                count++;
                a++;
            }
        }

        if (partner.getEmail() != null && !"".equals(partner.getEmail())) {
            if (crmPartnerService.findEmail(partner.getCreateUserId(), partner.getEmail(), partner.getPartnerType(), partner.getName()) > 0) {
                message.setData(0);
                count++;
            }
        }
        if (partner.getWeixin() != null && !"".equals(partner.getWeixin())) {
            if (crmPartnerService.findWeixin(partner.getCreateUserId(), partner.getWeixin(), partner.getPartnerType()) > 0) {
                message.setData(0);
                count++;
            }
        }
        if (("".equals(partner.getTelephone()) || partner.getTelephone() == null) && ("".equals(partner.getWeixin()) || partner.getWeixin() == null) && ("".equals(partner.getEmail()) || partner.getEmail() == null) && partner.getTelephoneList().size() == 0) {
            message.setData(1);
        } else if (count == 0) {
            crmPartnerService.add(partner);
            message.setData("添加成功");
        }
        return message;
    }

    @ApiOperation(value = "更新信息")
    @PostMapping("update")
    @ResponseBody
    public JsonMessage updatePartner(Authentication authentication, @RequestBody Partner partner) {
        JsonMessage message = new JsonMessage();
        AuthUserDetail detail = (AuthUserDetail) authentication.getDetails();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        partner.setTime(df.format(new Date()));
        List<String> id = crmPartnerService.partnerId(partner.getPartnerId());
        crmPartnerService.updateAll(partner.getName(), partner.getSex(), partner.getTelephone(), partner.getWeixin(), partner.getEmail(), partner.getTelephoneList(), id);
        crmPartnerService.update(partner);
        return message;
    }

    @ApiIgnore
    @GetMapping("createId")
    @ResponseBody
    public JsonMessage createId(Authentication authentication) {
        JsonMessage message = new JsonMessage();
        AuthUserDetail detail = (AuthUserDetail) authentication.getDetails();
        UserInfo user = new UserInfo();
        user.setUserId(detail.getUserId());
        user.setRoleId(detail.getRoleId());
        message.setData(user);
        return message;
    }

    @ApiOperation(value = "获取单个信息")
    @PostMapping("get")
    @ResponseBody
    public JsonMessage get(String partnerId) {
        JsonMessage message = new JsonMessage();
        crmPartnerService.get(partnerId);
        return message;
    }

    @ApiOperation(value = "删除单个信息")
    @PostMapping("remove")
    @ResponseBody
    public JsonMessage remove(String partnerId) {

        JsonMessage message = new JsonMessage();
        crmPartnerService.remove(partnerId);
        return message;
    }

    @ApiOperation(value = "减少号码")
    @PostMapping("reductions")
    @ResponseBody
    public JsonMessage reduction(String partnerId) {
        JsonMessage message = new JsonMessage();
        crmPartnerService.reduction(partnerId);
        return message;
    }

    @ApiIgnore
    @GetMapping("addInit")
    @ResponseBody
    public JsonMessage addInit() {
        JsonMessage message = new JsonMessage();
        Map<String, Object> map = new HashMap<>();
        Map<String, List<SysDict>> dictMap = dictService.findDictMap();
        map.putAll(dictMap);
        map.put("province", regionService.fillRegion(2));
        message.setData(map);
        return message;
    }

    @ApiIgnore
    @GetMapping("addInit1")
    @ResponseBody
    public JsonMessage addInit1() {
        JsonMessage message = new JsonMessage();
        Map<String, Object> map = new HashMap<>();
        Map<String, List<SysDict>> dictMap = dictService.findDictMap();
        map.putAll(dictMap);
        map.put("province", regionService.fillRegion(3));
        message.setData(map);
        return message;
    }

    @ApiIgnore
    @GetMapping("findInit")
    @ResponseBody
    public JsonMessage findInit(Authentication authentication, String partnerId) {
        JsonMessage message = new JsonMessage();
        AuthUserDetail detail = (AuthUserDetail) authentication.getDetails();
        Partner partner = crmPartnerService.get(partnerId);
        Map<String, Object> map = new HashMap<>();
        Map<String, List<SysDict>> dictMap = dictService.findDictMap();
        map.putAll(dictMap);
        if (!detail.getUserId().equals(partner.getCreateUserId())) {
            partner.setName(partner.getName().subSequence(0, 1) + "**");
            partner.setEmail("******@**.com");
            if (partner.getTelephone() != null && !"".equals(partner.getTelephone())) {
                partner.setTelephone(partner.getTelephone().subSequence(0, 3) + "*******");
            }
            if (partner.getWeixin() != null && !"".equals(partner.getWeixin())) {
                partner.setWeixin(partner.getWeixin().subSequence(0, 1) + "*******");
            }
            if (partner.getTelephoneList().size() > 0) {
                List<Telephone> t = JSON.parseArray(JSON.toJSONString(partner.getTelephoneList()),
                        Telephone.class);
                for (int i = 0; i < t.size(); i++) {
                    t.get(i).setTelephones("******");
                }
                partner.setTelephoneList(t);
            }
        }
        try {
            partner.getJusticeInfo().setName(partner.getJusticeInfo().getName().subSequence(0, 1) + "**");
            partner.getJusticeInfo().setTelephone(partner.getJusticeInfo().getTelephone().subSequence(0, 3) + "*** ***");

        } catch (Exception e) {
            System.out.println();
        }
        try {
            partner.getOrgInfo().setName(partner.getOrgInfo().getName().subSequence(0, 1) + "**");
            partner.getOrgInfo().setTelephone(partner.getOrgInfo().getTelephone().subSequence(0, 3) + "*** ***");
        } catch (Exception e) {
            System.out.println();
        }
        map.put("province", regionService.fillRegion(2));
        map.put("partner", partner);
        message.setData(map);
        return message;
    }

    @ApiIgnore
    @GetMapping("findInit1")
    @ResponseBody
    public JsonMessage findInit1(Authentication authentication, String partnerId) {
        JsonMessage message = new JsonMessage();
        AuthUserDetail detail = (AuthUserDetail) authentication.getDetails();
        Partner partner = crmPartnerService.get(partnerId);
        try {
            if (!detail.getUserId().equals(partner.getCreateUserId())) {
                partner.getJusticeInfo().setName(partner.getJusticeInfo().getName().subSequence(0, 1) + "**");
                partner.getJusticeInfo().setTelephone(partner.getJusticeInfo().getTelephone().subSequence(0, 3) + "*** ***");
            }
        } catch (Exception e) {
            System.out.println();
        }
        try {
            if (!detail.getUserId().equals(partner.getCreateUserId())) {

                partner.getOrgInfo().setName(partner.getOrgInfo().getName().subSequence(0, 1) + "**");
                partner.getOrgInfo().setTelephone(partner.getOrgInfo().getTelephone().subSequence(0, 3) + "*** ***");
            }
        } catch (
                Exception e) {
            System.out.println();
        }

        Map<String, Object> map = new HashMap<>();
        Map<String, List<SysDict>> dictMap = dictService.findDictMap();
        map.putAll(dictMap);
        if (!detail.getUserId().

                equals(partner.getCreateUserId())) {
            partner.setName(partner.getName().subSequence(0, 1) + "**");
            partner.setEmail("******@**.com");
            if (partner.getTelephone() != null && !"".equals(partner.getTelephone())) {
                partner.setTelephone(partner.getTelephone().subSequence(0, 3) + "*******");
            }
            if (partner.getWeixin() != null && !"".equals(partner.getWeixin())) {
                partner.setWeixin(partner.getWeixin().subSequence(0, 1) + "*******");
            }
            if (partner.getTelephoneList().size() > 0) {
                List<Telephone> t = JSON.parseArray(JSON.toJSONString(partner.getTelephoneList()),
                        Telephone.class);
                for (int i = 0; i < t.size(); i++) {
                    t.get(i).setTelephones("******");
                }
                partner.setTelephoneList(t);
            }
        }
        map.put("province", regionService.fillRegion(3));
        map.put("partner", partner);
        message.setData(map);
        return message;
    }

    @ApiIgnore
    @GetMapping("editInit")
    @ResponseBody
    public JsonMessage editInit(String partnerId) {
        JsonMessage message = new JsonMessage();
        Partner partner = crmPartnerService.get(partnerId);
        Map<String, Object> map = new HashMap<>();
        Map<String, List<SysDict>> dictMap = dictService.findDictMap();
        map.putAll(dictMap);
        map.put("province", regionService.fillRegion(2));
        map.put("partner", partner);
        message.setData(map);
        return message;
    }

    @ApiIgnore
    @GetMapping("editInit1")
    @ResponseBody
    public JsonMessage editInit1(String partnerId) {
        JsonMessage message = new JsonMessage();
        Partner partner = crmPartnerService.get(partnerId);
        Map<String, Object> map = new HashMap<>();
        Map<String, List<SysDict>> dictMap = dictService.findDictMap();
        map.putAll(dictMap);
        map.put("province", regionService.fillRegion(3));
        map.put("partner", partner);
        message.setData(map);
        return message;
    }

    @ApiOperation(value = "根据城市覆盖区域查询")
    @PostMapping("findByCity")
    @ResponseBody
    public JsonMessage findByCity(
            Authentication authentication,
            @RequestParam(value = "cities[]", required = false, defaultValue = "") String[] cities,
            Integer partnerType, @RequestParam(defaultValue = "1") int pageIndex,
            @RequestParam(defaultValue = "10") int pageSize) {
        // String cities[]={"320200","110100"};
        JsonMessage message = new JsonMessage();
        PageInfo<Partner> page = crmPartnerService.findByCity(partnerType, cities, pageIndex, pageSize);
        message.setData(page);
        return message;
    }


    /**
     * @param authentication
     * @param company        单位名称
     * @param partnerType    类型
     * @param belong         债权属性
     * @param cities         城市
     * @param orgType        机构类型
     * @param orgRemark      机构类型备注
     * @param typeId         业务类型
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @ApiIgnore
    @PostMapping("findAssetInf")
    @ResponseBody
    public JsonMessage findAssetInf(Authentication authentication, String depId, String createId,
                                    String company, Integer partnerType, String belong, @RequestParam(value = "cities[]", required = false, defaultValue = "") String[] cities, String orgType, String orgRemark, String typeId,
                                    @RequestParam(defaultValue = "1") int pageIndex,
                                    @RequestParam(defaultValue = "10") int pageSize) {
        AuthUserDetail detail = (AuthUserDetail) authentication.getDetails();
        JsonMessage message = new JsonMessage();
        PageInfo<Partner> page;
        String userId = "";
        //管理员
        if ("002".equals(detail.getRoleId())) {
            page = crmPartnerService.findAssetInf1(depId, createId, company, partnerType, belong, cities, orgType, orgRemark, typeId, pageIndex, pageSize);
        } else {
            page = crmPartnerService.findAssetInf(userId, detail.getUserId(), company, partnerType, belong, cities, orgType, orgRemark, typeId, pageIndex, pageSize);

        }
        message.setData(page);
        return message;
    }

    /**
     * @param authentication
     * @param company        单位名称
     * @param partnerType    类型
     * @param orgType        机构类型
     * @param orgRemark      机构类型备注
     * @param currency
     * @param incomeType
     * @param struct
     * @param scaleMin
     * @param scaleMax
     * @param deadline
     * @param cities
     * @param typeId         业务类型
     * @param typeName
     * @param incomeRate
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @ApiIgnore
    @PostMapping("findFundInfo")
    @ResponseBody
    public JsonMessage findFundInfo(Authentication authentication, String depId, String createId,
                                    String company, Integer partnerType, String orgType,
                                    String orgRemark, String currency,
                                    String incomeType,
                                    String struct, Integer scaleMin, Integer scaleMax,
                                    String deadline,
                                    @RequestParam(value = "cities[]", required = false, defaultValue = "") String[] cities,
                                    String typeId, String typeName, Integer incomeRate,
                                    @RequestParam(defaultValue = "1") int pageIndex,
                                    @RequestParam(defaultValue = "10") int pageSize) {
        AuthUserDetail detail = (AuthUserDetail) authentication.getDetails();
        JsonMessage message = new JsonMessage();

        PageInfo<Partner> page;
        String userId = "";
        //管理员
        if ("002".equals(detail.getRoleId())) {
            page = crmPartnerService.findFundInfo1(depId, createId, company, partnerType, orgType, orgRemark, currency, incomeType, struct, scaleMin, scaleMax, deadline, cities, typeId, typeName, incomeRate, pageIndex, pageSize);
        } else {
            page = crmPartnerService.findFundInfo(userId, detail.getUserId(), company, partnerType, orgType, orgRemark, currency, incomeType, struct, scaleMin, scaleMax, deadline, cities, typeId, typeName, incomeRate, pageIndex, pageSize);
        }
        message.setData(page);
        return message;
    }

    @ApiIgnore
    @PostMapping("path")
    @ResponseBody
    public JsonMessage path(Authentication authentication) {
        JsonMessage message = new JsonMessage();
        AuthUserDetail detail = (AuthUserDetail) authentication.getDetails();
        String roleId = detail.getRoleId();
        List<String> list = crmPartnerService.path(roleId);
        String depid = crmPartnerService.depId(detail.getUserId());

        if (!"001".equals(depid) && !"0011".equals(depid)) {
            list.remove("/audit");
            list.remove("/busSearch");
        }
        if (!"008".equals(depid))
        {
            list.remove("/bigProjectmana");
            list.remove("/perMan");
        }

//        if ("008".equals(depid))
//            list.remove("/projectmana");

        if ("001".equals(depid)&&"004".equals(roleId)){
            list.remove("/empCount");
            list.remove("/empPro");

        }

//        财务部员工项目
        if (!"009".equals(depid)&&!"004".equals(roleId)){
            list.remove("/empPro");
        }

        message.setData(list);
        return message;
    }
}
